//
//  OYCOAuthController.swift
//  WeiBo-Swift
//
//  Created by daniel on 2017/8/6.
//  Copyright © 2017年 daniel. All rights reserved.
//

import UIKit

class OYCOAuthController: UIViewController,UIWebViewDelegate {

    fileprivate var _webView: UIWebView?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        setupNav()
        setupWebView()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
}

extension OYCOAuthController {
    
    fileprivate func setupWebView() {
        
        let webView = UIWebView(frame: view.bounds)
        
        let urlRequest = URLRequest.init(url: OYCNetManager.sharedTools.oauthUrl, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
        webView.loadRequest(urlRequest)
        webView.delegate = self
        view.addSubview(webView)
        _webView = webView
    }
}


// MARK: - UIWebViewDelegate
extension OYCOAuthController {

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 1. 判断请求地址是否是百度，如果不是，继续加载
        guard let url = request.url, url.host == "www.baidu.com" else {
            return true
        }
        
        // 2. 判断请求地址的查询参数中是否包含 code=
        guard let query = url.query, query.hasPrefix("code=") else {
            print("取消")
            return false
        }
        
        // 3. 从查询字符串中取出授权码
        let code = query.substring(from: "code=".endIndex)
        
        OYCUserViewModel.shared.loadAccessToken(code: code) { (isSuccess) in
            if isSuccess {
                self.dismiss(animated: true, completion: nil)
                return
            }
            print("false")
        }
        
        return false
    }
}

extension OYCOAuthController {
    
    fileprivate func setupNav() {
        
        let leftItem = UIBarButtonItem.init(barButtonSystemItem: .stop, target: self, action: #selector(OYCOAuthController.leftItemClick))
        let rightItem = UIBarButtonItem.init(title: "自动填充", style: .plain, target: self, action: #selector(OYCOAuthController.rightItemClick))
        
        navigationItem.leftBarButtonItem = leftItem
        navigationItem.rightBarButtonItem = rightItem
        navigationItem.title = "授权登陆页"
    }
    
    @objc fileprivate func leftItemClick() {
        
        navigationController?.dismiss(animated: true, completion: nil)
        
    }
    
    @objc fileprivate func rightItemClick() {
        
        let javaScriptStr = "document.getElementById(\"userId\").value = \"775350532@qq.com\";document.getElementById(\"passwd\").value = \"hds110.bb\";"
        
        _webView?.stringByEvaluatingJavaScript(from: javaScriptStr)
    }
    
}
